package com.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// bean中有多个property子标签 , 因此 MutablePropertyValues 负责 存储/管理 PropertyValue
public class MutablePropertyValues implements Iterable<PropertyValue>{

    // 存储 PropertyValue
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        if (propertyValueList == null) {
            this.propertyValueList = new ArrayList<>();
        }else{
            this.propertyValueList = propertyValueList;
        }
    }

    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }

    // 获取所有 propertyValueList对象 , 返回 数组类型
    public PropertyValue[] getPropertyValueValues() {
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    // 根据 name属性值 , 获取 PropertyValue对象
    public PropertyValue getPropertyValue(String propertyName) {
        for (PropertyValue propertyValue : propertyValueList) {
            if (propertyValue.getName().equals(propertyName)) {
                return propertyValue;
            }
        }
        return null;
    }

    // 判断集合是否为空
    public boolean isEmpty() {
        return propertyValueList.isEmpty();
    }

    // 添加 PropertyValue对象 (链式编程)
    public MutablePropertyValues addPropertyValue(PropertyValue pv) {
        // pv 是否已存在 . 存在则覆盖
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue currPv = propertyValueList.get(i);
            if (currPv.getName().equals(pv.getName())) {
                propertyValueList.set(i , pv);
                return this;
            }
        }
        propertyValueList.add(pv);
        return this;
    }

    // 判断是否有name
    public boolean contains(String propertyName) {
        return getPropertyValue(propertyName) != null;
    }


}
